<template>
  <view>
    <!-- 悬浮按钮 -->
    <view class="floating-button" @click="openPopup">🤖</view>

    <!-- 弹窗 -->
    <uni-popup ref="popupRef" type="center">
      <view class="popup-container" @click.stop>
        <view class="popup-title">AI 学习建议</view>

        <!-- 建议内容 -->
        <!-- 可滚动内容区域 -->
        <scroll-view class="popup-content" scroll-y style="max-height: 500rpx; overflow: auto;"
          v-if="suggestion && Object.keys(suggestion).length">
          <view>
            <text>{{ suggestion.scheduleInfo }}</text>
            <view class="text" style="margin-top: 10rpx;">📘 课程数：{{ suggestion.courseCount }}</view>
            <view class="text" style="margin-top: 20rpx; white-space: pre-line;">📌 {{ suggestion.suggestion }}</view>
          </view>
        </scroll-view>

        <view v-else style="font-size: 28rpx; color: #999; margin-top: 20rpx;">
          暂无学习建议
        </view>


      </view>
    </uni-popup>
  </view>
</template>

<script setup>
  import {
    ref,
    watch,
    onMounted
  } from 'vue'

  // ✅ 接收 props
  const props = defineProps({
    userId: {
      type: String,
      required: true
    },
    week: {
      type: Number,
      required: true
    },
    dayOfWeek: {
      type: Number,
      required: true
    }
  })

  const popupRef = ref()
  const suggestion = ref({})

  // 弹出窗口
  // 打开弹窗前先加载数据
  async function openPopup() {
    // 显示加载中
    uni.showLoading({
      title: '加载中...',
      mask: true
    })

    const success = await fetchSuggestion()

    uni.hideLoading() // 无论成功失败都关闭 loading

    if (success) {
      popupRef.value.open('center') // ✅ 只在成功时弹出弹窗
    }
  }

  // 拉取学习建议
  async function fetchSuggestion() {
    if (!props.userId || !props.week || !props.dayOfWeek) return

    try {
      // // 👇 显示加载中提示
      // uni.showLoading({
      //   title: '加载中...',
      //   mask: true // 防止用户点击其他区域
      // })
      const res = await uni.request({
        url: `http://47.122.53.1:80/course/ai-suggestion/${props.userId}/${props.week}?dayOfWeek=${props.dayOfWeek}`,
        method: 'GET'
      })

      console.log('✅ 接口响应原始数据:', res)
      suggestion.value = res.data.data || {}
      return true // ✅ 成功
    } catch (err) {
      console.error('❌ 获取建议失败:', err)
      uni.showToast({
        title: '获取失败',
        icon: 'error'
      })
      suggestion.value = {}
      return false // ❌ 失败
    }
  }


  // 监听 week/dayOfWeek 变化时更新建议
  watch([() => props.week, () => props.dayOfWeek], () => {
    if (popupRef.value) fetchSuggestion()
  })

  // 初次挂载时可选自动加载（可根据需求保留）
  // onMounted(() => {
  //   if (popupRef.value) fetchSuggestion()
  // })
</script>


<style lang="scss" scoped>
  .floating-button {
    position: fixed;
    bottom: 200rpx;
    right: 50rpx;
    width: 90rpx;
    height: 90rpx;
    border-radius: 50%;
    background-color: var(--primary-color);
    color: #fff;
    font-size: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }

  .popup-container {
    padding: 40rpx;
    width: 600rpx;
    background: #fff;
    border-radius: 20rpx;
  }



  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }

  .popup-content {
    font-size: 28rpx;
    white-space: pre-line;
    margin-top: 20rpx;

    .text {
      padding: 20rpx;
      color: #333;


    }
  }

  /* 隐藏滚动条，仅适用于支持 WebKit 的平台（如微信小程序/H5） */
  .popup-content::-webkit-scrollbar {
    display: none;
  }

  .popup-footer {
    margin-top: 30rpx;
    text-align: right;
  }
</style>